package com.baidu.foodrecipe.ui.fragment.favorite

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.baidu.foodrecipe.data.local.entity.FavoriteEntity
import com.baidu.foodrecipe.data.model.Result
import com.baidu.foodrecipe.data.repository.Repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class FavoriteViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = Repository(application)
    var favoriteRecipes: MutableLiveData<List<FavoriteEntity>> = MutableLiveData()

    fun loadFavorites() {
        viewModelScope.launch {
            repository.getFavoriteRecipes().collect {
                favoriteRecipes.value = it
            }
        }
    }

    fun addFavoriteRecipe(result: Result, callback: (start: Boolean) -> Unit = {}) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.insertFavoriteRecipe(FavoriteEntity(result), callback)
        }
    }

    //判断是否被收藏
    fun isFavorited(result: Result): Boolean {
        favoriteRecipes.value?.let { resultEntities ->
            for (entity in resultEntities) {
                if (entity.result.id == result.id) {
                    return true
                }
            }
        }
        return false
    }

    fun removeFavoriteRecipe(position: Int) {
        favoriteRecipes.value?.let { resultEntities ->
            viewModelScope.launch(Dispatchers.IO) {
                repository.removeFavoriteRecipe(resultEntities[position])
            }
        }
    }

    fun removeFavoriteRecipe(result: Result, callback: (start: Boolean) -> Unit = {}) {
        favoriteRecipes.value?.let { resultEntities ->
            for (entity in resultEntities) {
                if (entity.result.id == result.id) {
                    viewModelScope.launch(Dispatchers.IO) {
                        repository.removeFavoriteRecipe(entity, callback)
                    }
                }
            }
        }
    }

    fun deleteAllFavorites() {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteAllFavoriteRecipes()
        }
    }
}